import { ref, onMounted, onUnmounted, computed } from "vue";
import { filter } from "../util/todoStorage";

const validHash = ["all", "active", "completed"];

export default function useFilter(todosRef) {
  const visiblityRef = ref("all");

  const onHashchange = () => {
    //从地址栏获取值
    const hash = location.hash.replace(/#\/?/, "");
    if (validHash.includes(hash)) {
      //合法的
      visiblityRef.value = hash;
    } else {
      //默认为all
      location.hash = "";
      visiblityRef.value = "all";
    }
  };
  //监控地址栏变化
  onMounted(() => {
    window.addEventListener("hashchange", onHashchange);
    onHashchange();
  });
  onUnmounted(() => {
    window.removeEventListener("hashchange", onHashchange);
  });
  const filteredRef = computed(() => {
    return filter(todosRef.value, visiblityRef.value);
  });
  const remainingRef = computed(() => {
    return filter(todosRef.value, "active").length;
  });
  const completedRef = computed(() => {
    return filter(todosRef.value, "completed").length;
  });
  return {
    visiblityRef,
    filteredRef,
    remainingRef,
    completedRef,
  };
}
